package BackTrackingSeries;

import java.util.ArrayList;
import java.util.List;

public class GenerateParenthesisSolution_22 {
    List<String> result = new ArrayList<>();
    StringBuilder path = new StringBuilder();

    public List<String> generateParenthesis(int n) {
        backTracking(n, 0, 0, path);
        return result;
    }

    public void backTracking(int n, int left, int right, StringBuilder path) {
        // 回溯终止条件：
        //1、左括号的数量l < 右括号的数量r
        if (left < right) {
            return;
        }

        //2、l = r = 说明已经是合法结果
        if (path.length() == 2 * n) {
            result.add(path.toString());
        }

        // 分支回溯
        if (left < n) {
            path.append("(");
            backTracking(n, left + 1, right, path);
            path.deleteCharAt(path.length() - 1);
        }

        if (right < n) {
            path.append(")");
            backTracking(n, left, right + 1, path);
            path.deleteCharAt(path.length() - 1);
        }
    }
}
